<template>
  <div class="performance-analysis-page">
    <!-- GMV分析 -->
    <el-card class="chart-card">
      <template #header>GMV 与订单数趋势（最近7天）</template>
      <div ref="gmvChartRef" class="chart"></div>
    </el-card>

    <!-- 订单分析 -->
    <el-card class="chart-card">
      <template #header>订单状态分布</template>
      <div ref="orderStatusChartRef" class="chart"></div>
    </el-card>

    <!-- 用户活跃度分析 -->
    <el-card class="chart-card">
      <template #header>用户活跃度分析</template>
      <div class="user-activity">
        <div class="activity-metrics">
          <div class="activity-item">
            <div class="activity-value">{{ userData.totalUsers }}</div>
            <div class="activity-label">总用户数</div>
          </div>
          <div class="activity-item">
            <div class="activity-value">{{ userData.newUsers }}</div>
            <div class="activity-label">最近7天新增</div>
          </div>
          <div class="activity-item">
            <div class="activity-value">{{ userData.newUsers30 }}</div>
            <div class="activity-label">最近30天新增</div>
          </div>
        </div>
        <div ref="userGrowthChartRef" class="chart"></div>
      </div>
    </el-card>

    <!-- 商品库存分析 -->
    <el-card class="chart-card">
      <template #header>商品库存状态</template>
      <div class="inventory-analysis">
        <div class="inventory-summary">
          <div class="inventory-item">
            <el-tag type="success">{{ inventoryData.inStock }}</el-tag>
            <span>有库存</span>
          </div>
          <div class="inventory-item">
            <el-tag type="warning">{{ inventoryData.lowStock }}</el-tag>
            <span>库存不足</span>
          </div>
          <div class="inventory-item">
            <el-tag type="danger">{{ inventoryData.outOfStock }}</el-tag>
            <span>缺货</span>
          </div>
        </div>
        <div ref="inventoryChartRef" class="chart"></div>
      </div>
    </el-card>

    <!-- 时间分布分析 -->
    <el-card class="chart-card">
      <template #header>订单时间分布</template>
      <div ref="timeDistributionChartRef" class="chart"></div>
    </el-card>

    <!-- 地区分布分析 -->
    <el-card class="chart-card">
      <template #header>订单地区分布</template>
      <div ref="regionChartRef" class="chart"></div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts/core'
import { LineChart, BarChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { onMounted, ref, reactive } from 'vue'
import { reportService, type SalesTrendData, type UserStatisticsData, type OrderStatusData, type InventoryStatusData, type TimeDistributionData, type RegionDistributionData } from '@/api/reportService'

echarts.use([
  LineChart,
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  CanvasRenderer,
])

const gmvChartRef = ref<HTMLDivElement | null>(null)
const orderStatusChartRef = ref<HTMLDivElement | null>(null)
const userGrowthChartRef = ref<HTMLDivElement | null>(null)
const inventoryChartRef = ref<HTMLDivElement | null>(null)
const timeDistributionChartRef = ref<HTMLDivElement | null>(null)
const regionChartRef = ref<HTMLDivElement | null>(null)

const salesData = reactive<SalesTrendData>({
  dates: [],
  orderCounts: [],
  dailyGmv: []
})

const userData = reactive<UserStatisticsData>({
  totalUsers: 0,
  newUsers: 0,
  newUsers30: 0,
  dates: [],
  dailyNewUsers: []
})

const orderStatusData = reactive<OrderStatusData>({
  statusNames: [],
  counts: []
})

const inventoryData = reactive<InventoryStatusData>({
  inStock: 0,
  lowStock: 0,
  outOfStock: 0
})

const timeDistributionData = reactive<TimeDistributionData>({
  hours: [],
  counts: []
})

const regionDistributionData = reactive<RegionDistributionData>({
  provinces: [],
  counts: []
})

const loadSalesData = async () => {
  try {
    const data = await reportService.getSalesTrend()
    Object.assign(salesData, data)
    initGmvChart()
  } catch (error) {
    console.error('加载销售数据失败:', error)
  }
}

const loadUserData = async () => {
  try {
    const data = await reportService.getUserStatistics()
    Object.assign(userData, data)
    initUserGrowthChart()
  } catch (error) {
    console.error('加载用户数据失败:', error)
  }
}

const loadOrderStatusData = async () => {
  try {
    const data = await reportService.getOrderStatusDistribution()
    Object.assign(orderStatusData, data)
    initOrderStatusChart()
  } catch (error) {
    console.error('加载订单状态数据失败:', error)
  }
}

const loadInventoryData = async () => {
  try {
    const data = await reportService.getInventoryStatus()
    Object.assign(inventoryData, data)
    initInventoryChart()
  } catch (error) {
    console.error('加载库存数据失败:', error)
  }
}

const loadTimeDistributionData = async () => {
  try {
    const data = await reportService.getOrderTimeDistribution()
    Object.assign(timeDistributionData, data)
    initTimeDistributionChart()
  } catch (error) {
    console.error('加载时间分布数据失败:', error)
  }
}

const loadRegionDistributionData = async () => {
  try {
    const data = await reportService.getOrderRegionDistribution()
    Object.assign(regionDistributionData, data)
    initRegionChart()
  } catch (error) {
    console.error('加载地区分布数据失败:', error)
  }
}

const initGmvChart = () => {
  if (!gmvChartRef.value) return
  
  const chart = echarts.init(gmvChartRef.value)
  chart.setOption({
    tooltip: { 
      trigger: 'axis',
      axisPointer: { type: 'cross' }
    },
    legend: { 
      data: ['GMV(¥)', '订单数'],
      bottom: 0
    },
    grid: { 
      left: 30, 
      right: 20, 
      top: 20, 
      bottom: 50 
    },
    xAxis: { 
      type: 'category', 
      data: salesData.dates,
      axisLabel: { rotate: 45 }
    },
    yAxis: [
      { 
        type: 'value', 
        name: 'GMV(¥)',
        position: 'left'
      },
      { 
        type: 'value', 
        name: '订单数',
        position: 'right'
      }
    ],
    series: [
      {
        name: 'GMV(¥)',
        type: 'line',
        yAxisIndex: 0,
        smooth: true,
        data: salesData.dailyGmv,
        itemStyle: { color: '#67C23A' },
        areaStyle: { 
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(103, 194, 58, 0.3)' },
              { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }
            ]
          }
        }
      },
      {
        name: '订单数',
        type: 'bar',
        yAxisIndex: 1,
        data: salesData.orderCounts,
        itemStyle: { color: '#409EFF' }
      }
    ]
  })
}

const initOrderStatusChart = () => {
  if (!orderStatusChartRef.value) return
  
  const chart = echarts.init(orderStatusChartRef.value)
  chart.setOption({
    tooltip: { trigger: 'item' },
    legend: { bottom: 0 },
    series: [
      {
        name: '订单状态',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: orderStatusData.statusNames.map((name, index) => ({
          name,
          value: orderStatusData.counts[index]
        }))
      }
    ]
  })
}

const initUserGrowthChart = () => {
  if (!userGrowthChartRef.value) return
  
  const chart = echarts.init(userGrowthChartRef.value)
  chart.setOption({
    tooltip: { trigger: 'axis' },
    grid: { 
      left: 30, 
      right: 20, 
      top: 20, 
      bottom: 30 
    },
    xAxis: { 
      type: 'category', 
      data: userData.dates,
      axisLabel: { rotate: 45 }
    },
    yAxis: { type: 'value' },
    series: [
      {
        type: 'line',
        smooth: true,
        data: userData.dailyNewUsers,
        itemStyle: { color: '#E6A23C' },
        areaStyle: { 
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(230, 162, 60, 0.3)' },
              { offset: 1, color: 'rgba(230, 162, 60, 0.1)' }
            ]
          }
        }
      }
    ]
  })
}

const initInventoryChart = () => {
  if (!inventoryChartRef.value) return
  
  const chart = echarts.init(inventoryChartRef.value)
  chart.setOption({
    tooltip: { trigger: 'item' },
    legend: { bottom: 0 },
    series: [
      {
        name: '库存状态',
        type: 'pie',
        radius: '60%',
        data: [
          { name: '有库存', value: inventoryData.inStock, itemStyle: { color: '#67C23A' } },
          { name: '库存不足', value: inventoryData.lowStock, itemStyle: { color: '#E6A23C' } },
          { name: '缺货', value: inventoryData.outOfStock, itemStyle: { color: '#F56C6C' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })
}

const initTimeDistributionChart = () => {
  if (!timeDistributionChartRef.value) return
  
  const chart = echarts.init(timeDistributionChartRef.value)
  chart.setOption({
    tooltip: { trigger: 'axis' },
    grid: { 
      left: 30, 
      right: 20, 
      top: 20, 
      bottom: 30 
    },
            xAxis: { 
          type: 'category', 
          data: timeDistributionData.hours
        },
        yAxis: { type: 'value' },
        series: [
          {
            type: 'bar',
            data: timeDistributionData.counts,
            itemStyle: { color: '#409EFF' }
          }
        ]
  })
}

const initRegionChart = () => {
  if (!regionChartRef.value) return
  
  const chart = echarts.init(regionChartRef.value)
  chart.setOption({
    tooltip: { trigger: 'item' },
    legend: { bottom: 0 },
    series: [
      {
        name: '地区分布',
        type: 'pie',
        radius: '60%',
        data: regionDistributionData.provinces.map((province, index) => ({
          name: province,
          value: regionDistributionData.counts[index]
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })
}

onMounted(async () => {
  await Promise.all([
    loadSalesData(),
    loadUserData(),
    loadOrderStatusData(),
    loadInventoryData(),
    loadTimeDistributionData(),
    loadRegionDistributionData()
  ])
})
</script>

<style scoped>
.performance-analysis-page {
  padding: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 20px;
}

.chart-card {
  min-height: 400px;
}

.chart {
  width: 100%;
  height: 300px;
}

.user-activity {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.activity-metrics {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.activity-item {
  text-align: center;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.activity-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.activity-label {
  font-size: 14px;
  color: #606266;
}

.inventory-analysis {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.inventory-summary {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.inventory-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.inventory-item span {
  font-size: 14px;
  color: #606266;
}

@media (max-width: 768px) {
  .performance-analysis-page {
    grid-template-columns: 1fr;
  }
  
  .activity-metrics {
    grid-template-columns: 1fr;
  }
  
  .inventory-summary {
    flex-direction: column;
    gap: 20px;
  }
}
</style>
